package com.tiyo.wechat.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiyo.common.utils.http.HttpUtils;

public class WechatUtil {
	static ObjectMapper mapper = new ObjectMapper();
	private static final Logger log = LoggerFactory.getLogger(WechatUtil.class);
	/**
	 * 获取微信AccessToken
	 */
	private static  String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
	private static String getTokenUrl(String appId, String appSecret) {
		return String.format(ACCESS_TOKEN, appId, appSecret);
	}
	/**
	 * 
	 *  @Description:获取微信ACCESSTOKEN
	 *  @author yangb  
	 *  @date 2022年7月26日 下午3:26:35 
	 *  @param appId
	 *  @param appSecret
	 *  @return
	 */
	public static AccessTokenResponse getToken(String appId, String appSecret) {
		String url = getTokenUrl(appId, appSecret);
		AccessTokenResponse response=new AccessTokenResponse();
		String jsonStr=HttpUtils.sendGet(url);
		log.info("通过【{}】【{}】获取微信Token:{}",appId,appSecret,jsonStr);
		JSONObject jsonObject=JSONObject.parseObject(jsonStr);
		if(jsonObject.containsKey("access_token")) {
			response.setErrcode("0");
			response.setAccess_token(jsonObject.getString("access_token"));
			response.setExpires_in(jsonObject.getInteger("expires_in"));
		} else {
			response.setErrcode(jsonObject.getString("errcode"));
			response.setErrmsg(jsonObject.getString("errmsg"));
		}
		return response;
	}
	@JsonIgnoreProperties(ignoreUnknown = true)
	public static class AccessTokenResponse{
		/**返回状态码  0 为成功 其他为失败**/
		private String errcode;
		/**错误信息**/
		private String errmsg;
		/**微信公众号TOKEN**/
		private String access_token;
		/**有效期时长 秒**/
		private Integer expires_in;
		public String getErrcode() {
			return errcode;
		}
		public void setErrcode(String errcode) {
			this.errcode = errcode;
		}
		public String getErrmsg() {
			return errmsg;
		}
		public void setErrmsg(String errmsg) {
			this.errmsg = errmsg;
		}
		public String getAccess_token() {
			return access_token;
		}
		public void setAccess_token(String access_token) {
			this.access_token = access_token;
		}
		public Integer getExpires_in() {
			return expires_in;
		}
		public void setExpires_in(Integer expires_in) {
			this.expires_in = expires_in;
		}
	}
	/**获取微信jsticketURL**/
	private static  String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";
	private static String getJsapiTicketUrl(String token) {
		return String.format(JSAPI_TICKET_URL, token);
	}
	/**
	 * 
	 *  @Description:获取jsApiTicket
	 *  @author yangb  
	 *  @date 2022年7月26日 下午3:27:41 
	 *  @param token
	 *  @return
	 */
	public static JSApiResponse getJsapiTicket(String token) {
		String url = getJsapiTicketUrl(token);
		JSApiResponse response=new JSApiResponse();
		String jsonStr=HttpUtils.sendGet(url);
		log.info("通过【{}】获取JSAPITicket:{}",token,jsonStr);
		try {
			return mapper.readValue(jsonStr, JSApiResponse.class);
		} catch (Exception e) {
			log.error("获取Wechat-JSAPITicket失败",e);
			response = new JSApiResponse();
			response.setErrcode("99999");
			response.setErrmsg(e.getMessage());
		}
		return response;
		
	}
	@JsonIgnoreProperties(ignoreUnknown = true)
	public static class JSApiResponse {
		private String errcode;
		private String errmsg;
		private String ticket;
		private Integer expires_in;
		public String getErrcode() {
			return errcode;
		}
		public void setErrcode(String errcode) {
			this.errcode = errcode;
		}
		public String getErrmsg() {
			return errmsg;
		}
		public void setErrmsg(String errmsg) {
			this.errmsg = errmsg;
		}
		public String getTicket() {
			return ticket;
		}
		public void setTicket(String ticket) {
			this.ticket = ticket;
		}
		public Integer getExpires_in() {
			return expires_in;
		}
		public void setExpires_in(Integer expires_in) {
			this.expires_in = expires_in;
		}
		
	}
	private static  String USER_OPENID = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
	private static String getUserOpenIdUrl(String appId, String appSecret, String code) {
		return String.format(USER_OPENID, appId, appSecret, code);
	}
	/**
	 * 
	 *  @Description:获取用户openId
	 *  @author yangb  
	 *  @date 2022年7月26日 下午4:30:24 
	 *  @param appId
	 *  @param appSecret
	 *  @param code
	 *  @return
	 */
	public static UserOpenIdResponse getUserOpenId(String appId, String appSecret, String code) {
		String url = getUserOpenIdUrl(appId, appSecret, code);
		String jsonStr=HttpUtils.sendGet(url);
		log.info("通过【{}】获取用户OpenId:{}",code,jsonStr);
		UserOpenIdResponse response = new UserOpenIdResponse();
		JSONObject jsonObject=JSONObject.parseObject(jsonStr);
		if(jsonObject.containsKey("errcode")) {
			response.setErrcode(jsonObject.getString("errcode"));
			response.setErrmsg(jsonObject.getString("errmsg"));
		} else {
			response.setErrcode("0");
			response.setAccess_token(jsonObject.getString("access_token"));
			response.setExpires_in(jsonObject.getInteger("expires_in"));
			response.setRefresh_token(jsonObject.getString("refresh_token"));
			response.setOpenid(jsonObject.getString("openid"));
			response.setScope(jsonObject.getString("scope"));
			response.setUnionid(jsonObject.getString("unionid"));
		}
		return response;
	}
	@JsonIgnoreProperties(ignoreUnknown = true)
	public static class UserOpenIdResponse{
		private String access_token;
		private Integer expires_in;
		private String refresh_token;
		private String openid;
		private String scope;
		private String unionid;
		private String errcode;
		private String errmsg;
		public String getAccess_token() {
			return access_token;
		}
		public void setAccess_token(String access_token) {
			this.access_token = access_token;
		}
		public Integer getExpires_in() {
			return expires_in;
		}
		public void setExpires_in(Integer expires_in) {
			this.expires_in = expires_in;
		}
		public String getRefresh_token() {
			return refresh_token;
		}
		public void setRefresh_token(String refresh_token) {
			this.refresh_token = refresh_token;
		}
		public String getOpenid() {
			return openid;
		}
		public void setOpenid(String openid) {
			this.openid = openid;
		}
		public String getScope() {
			return scope;
		}
		public void setScope(String scope) {
			this.scope = scope;
		}
		public String getUnionid() {
			return unionid;
		}
		public void setUnionid(String unionid) {
			this.unionid = unionid;
		}
		public String getErrcode() {
			return errcode;
		}
		public void setErrcode(String errcode) {
			this.errcode = errcode;
		}
		public String getErrmsg() {
			return errmsg;
		}
		public void setErrmsg(String errmsg) {
			this.errmsg = errmsg;
		}
		
	}
	private static  String SENDMESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
	private static String getSendMsgUrl(String token) {
		return String.format(SENDMESSAGE_URL, token);
	}
	/**
	 * 
	 *  @Description:微信模版消息推送
	 *  @author yangb  
	 *  @date 2022年7月26日 下午5:10:38 
	 *  @param token
	 *  @param message
	 *  @return
	 */
	public static MessageResponse sendMsg(String token, JSONObject json) {
		MessageResponse resepose = new MessageResponse();
		try {
			String url = getSendMsgUrl(token);
			String jsonStr = HttpUtils.sendPost(url,  json.toJSONString());
			log.info("微信公众号推送返回：" + jsonStr);
			resepose = mapper.readValue(jsonStr, MessageResponse.class);
			resepose.setResponse(jsonStr);
			return resepose;
		} catch (Exception e) {
			log.info("微信公众号推送失败：" + json.toJSONString(),e);
			resepose.setErrcode("-1");
			resepose.setErrmsg(e.getMessage());
		}
		return resepose;
	}
	@JsonIgnoreProperties(ignoreUnknown = true)
	public static class MessageResponse {
		private String errcode;
		private String errmsg;
		private String msgid;
		private String response;
		public String getErrcode() {
			return errcode;
		}
		public void setErrcode(String errcode) {
			this.errcode = errcode;
		}
		public String getErrmsg() {
			return errmsg;
		}
		public void setErrmsg(String errmsg) {
			this.errmsg = errmsg;
		}
		public String getMsgid() {
			return msgid;
		}
		public void setMsgid(String msgid) {
			this.msgid = msgid;
		}
		public String getResponse() {
			return response;
		}
		public void setResponse(String response) {
			this.response = response;
		}
		
	}
}
